package com.yuanluludev.lib_base.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import com.gyf.immersionbar.ImmersionBar
import com.yuanluludev.lib_base.R
import com.yuanluludev.lib_base.action.BundleAction
import com.yuanluludev.lib_base.action.ClickAction
import com.yuanluludev.lib_base.action.KeyboardAction
import com.yuanluludev.lib_base.widget.TitleBarView

/**
 * 不带网络的碎片基类
 * yuanLuLu
 */
abstract class BaseFragment : Fragment(),
    ClickAction, BundleAction, KeyboardAction {

    /**
     * 是否需要使用DataBinding 供子类修改，用户请慎动
     */
    private var isUseDB = false
    protected var mContext: Context? = null

    /** 根布局 */
    private var rootView: View? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return if (!isUseDB) {
            inflater.inflate(getLayoutResId(), container, false)
        } else {
            initViewModel()
            //with view data binding
            if (this is BaseVMWithDBFragment<*, *>) {
                initDataBinding(inflater, container)?.root
            } else {
                inflater.inflate(getLayoutResId(), container, false)
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        dealCommonEvent(view)

        initData()
        initEvents()
        initEvents(view)

    }

    private fun dealCommonEvent(view: View) {
        //赋值根布局
        rootView = view
        // 处理页面返回按钮点击事件
        view.findViewById<TitleBarView?>(R.id.titleBar)?.let {
            it.setOnLeftBtnClickListener { activity?.finish() }
        }
        // 初始化沉浸式状态栏
        if (isStatusBarEnabled()) {
            getStatusBarConfig().init()

            view.findViewById<View?>(R.id.rootLayout)?.let {
                ImmersionBar.setTitleBar(this, it)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (isStatusBarEnabled()) {
            // 重新初始化状态栏
            getStatusBarConfig().init()
        }
    }

    /**
     * 根据资源 id 获取一个 View 对象
     */
    override fun <V : View?> findViewById(@IdRes id: Int): V? {
        return rootView?.findViewById(id)
    }

    override fun getBundle(): Bundle? {
        return arguments
    }

    open fun initEvents(view: View) {}
    open fun initEvents() {}
    open fun initData() {}

    abstract fun getLayoutResId(): Int

    fun useDataBinding(isUseDB: Boolean) {
        this.isUseDB = isUseDB
    }

    /**
     * 让子类初始化DataBinding(BaseVMWithDataBinding)
     */
    open fun initDataBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): ViewDataBinding? = null

    /**
     * 让子类初始化ViewModel
     */
    open fun initViewModel() {}

    open fun showLoading(loadingTip: String = "正在加载...", isCancelable: Boolean = false) =
        (mContext as BaseActivity?)?.showLoading(loadingTip, isCancelable)

    open fun hideLoading() = (mContext as BaseActivity?)?.hideLoading()

    override fun onDestroyView() {
        super.onDestroyView()
        rootView = null
    }

    /**
     * startActivityForResult 方法优化
     */
    open fun startActivityForResult(
        clazz: Class<out Activity>,
        callback: BaseActivity.OnActivityCallback?
    ) {
        (mContext as BaseActivity?)?.startActivityForResult(clazz, callback)
    }

    open fun startActivityForResult(intent: Intent, callback: BaseActivity.OnActivityCallback?) {
        (mContext as BaseActivity?)?.startActivityForResult(intent, null, callback)
    }

    open fun startActivityForResult(
        intent: Intent,
        options: Bundle?,
        callback: BaseActivity.OnActivityCallback?
    ) {
        (mContext as BaseActivity?)?.startActivityForResult(intent, options, callback)
    }


    //---------------status bar -----------

    /** 状态栏沉浸 */
    private var immersionBar: ImmersionBar? = null

    /**
     * 是否在 Fragment 使用沉浸式
     */
    open fun isStatusBarEnabled() = false

    /**
     * 获取状态栏字体颜色 (默认白色)
     */
    protected open fun isStatusBarDarkFont() = false

    /**
     * 状态栏背景颜色
     */
    open fun getStatusBarBacColor() = R.color.color_primary
    /**
     * 导航栏背景颜色
     */
    open fun getNavigationBarBacColor() = R.color.color_primary

    /**
     * 获取状态栏沉浸的配置对象
     */
    protected fun getStatusBarConfig(): ImmersionBar {
        if (immersionBar == null) {
            immersionBar = createStatusBarConfig()
        }
        return immersionBar!!
    }

    /**
     * 初始化沉浸式
     */
    protected fun createStatusBarConfig(): ImmersionBar {
        return ImmersionBar.with(this)
            // 默认状态栏字体颜色为黑色
            .statusBarDarkFont(isStatusBarDarkFont())
            .statusBarColor(getStatusBarBacColor())
            // 指定导航栏背景颜色
            .navigationBarColor(getNavigationBarBacColor())
        // 状态栏字体和导航栏内容自动变色，必须指定状态栏颜色和导航栏颜色才可以自动变色
//            .autoDarkModeEnable(true, 0.2f)
    }

}